import { useEffect, useMemo } from "react";
import { useSelector, useDispatch } from "react-redux";
import { add, sub, reSetState } from "@/store/counter.js";
import { increase } from "@/store/table.js";
import { getContent, postContent, getTableData } from "@/service/api.js";

const Person = () => {
  useEffect(() => {
    dispatch(
      getContent({
        name: "mock",
        age: 12,
      }),
    );
    dispatch(
      postContent({
        status: "请求状态测试",
      }),
    );
    dispatch(getTableData());
  }, []);
  useEffect(() => {
    return () => {
      dispatch(reSetState());
      console.log("user组件被卸载");
    };
  }, []);
  const dispatch = useDispatch();
  //两个title  解构重命名
  const {
    title: counterTitle,
    counter,
    name,
  } = useSelector((state) => state.counterStore);
  const { tableData, title: tableTitle } = useSelector(
    (state) => state.tableStore,
  );
  const total = useMemo(() => {
    return counter ** 2;
  }, [counter]);
  return (
    <div>
      <div>{counterTitle}</div>
      <div>{name}</div>
      <div>counter:{counter}</div>
      <div>counter的平方:{total}</div>
      <button onClick={() => dispatch(add())}>add</button>
      <button onClick={() => dispatch(sub(2))}>sub</button>
      <button onClick={() => dispatch(increase())}>increase</button>
      <button>{tableTitle}</button>
      <div>
        {tableData.map((item, index) => {
          return (
            <div key={index}>
              <span>{item.name}</span>
              <span>{item.age}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
};
export default Person;
